<template>
  <!-- 登录日志 -->
  <div class="manage_container">
    <div class="manage_table">
      <el-table
        ref="loginlogTable"
        :data="tableData"
        class="_table"
        table-layout="fixed"
        :border="false"
        v-loading="loading"
        :default-sort="defaultSort"
        @sort-change="handleSortChange"
        @selection-change="handleSelectionChange"
        @row-click="currentRowChange"
        height="75vh"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="infoId" label="访问编号" />
        <el-table-column
          label="用户名"
          prop="userName"
          :show-overflow-tooltip="true"
          sortable="custom"
          :sort-orders="['descending', 'ascending']"
        />
        <el-table-column prop="ipaddr" label="地址" />

        <el-table-column
          label="登录地点"
          prop="loginLocation"
          :show-overflow-tooltip="true"
        />
        <el-table-column prop="os" label="操作系统" />
        <el-table-column prop="browser" label="浏览器" />

        <el-table-column prop="status" label="登录状态" width="150">
          <template #default="scope">
            <dictTag :options="sys_common_status" :value="scope.row.status" />
            <!-- {{ scope.row.status }} -->
          </template>
        </el-table-column>
        <el-table-column
          label="描述"
          prop="msg"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="访问时间"
          prop="loginTime"
          sortable="custom"
          :sort-orders="['descending', 'ascending']"
        >
          <template #default="scope">
            <span>{{ scope.row.loginTime }}</span>
          </template>
        </el-table-column>
      </el-table>

      <div class="page d-f jc-fe">
        总{{ total }}条数据
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 40, 50, 100, 200]"
          :size="size"
          :disabled="disabled"
          :background="background"
          layout=" prev, pager, next, sizes"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :hide-on-single-page="hide"
        />
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted, nextTick } from "vue";
// import Breadcrumb from "@/components/breadcrumb.vue";
// import Check from "./components/check.vue";
import dictTag from "@/components/dictTag.vue";
import { downloadFile } from "@/utils/download";
import { parseTime } from "@/utils/common.js";

import { getLogList, delLog, cleanLog } from "@/api/loginLog.js";
import {
  Plus,
  Search,
  Upload,
  Download,
  Delete,
  Unlock,
  Refresh,
  View,
} from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
// import { piniaPluginPersist } from "@/stores/modules/piniaPluginPersist";
import { useDict } from "@/utils/dict.js";
const { sys_common_status } = useDict("sys_common_status");
const defaultSort = ref({ prop: "operTime", order: "descending" });
const loading = ref(true);
const tableData = ref([]);
const selectedLLogIds = ref([]);
const loginlogTable = ref(null);
const multiple = ref(true);
const curUser = ref("");
const once = ref(true);
// 多选框选中数据
function handleSelectionChange(selection) {
  selectedLLogIds.value = selection.map((item) => item.infoId);
  multiple.value = !selection.length;
  if (selection.length == 1) {
    once.value = false;
  } else {
    once.value = true;
  }
}
const currentRowChange = (curRow) => {
  console.log(curRow);
  const flag = selectedLLogIds.value.includes(curRow.infoId);
  loginlogTable.value.toggleRowSelection(curRow, !flag);
  curUser.value = curRow.userName;
};

const filtrateData = ref({});
// 排序触发
const setCondition2 = () => {
  const data = filtrateData.value;
  data.pageSize = pageSize.value;
  data.pageNum = currentPage.value;
  loading.value = true;
  getLoginLogList(data);
};

const deleteSelectedLog = () => {
  // 获取勾选内容
  const selectedIds = selectedLLogIds.value.join(",");
  if (selectedIds == "") return ElMessage.error("请选择日志项");
  console.log(selectedIds);
  ElMessageBox.confirm("确认要删除这些日志?", "删除系统访问日志", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    // type: "warning",
    icon: "WarnTriangleFilled",
  })
    .then(() => {
      delLog(selectedIds).then((res) => {
        if (res.code == 200) {
          ElMessage({
            message: "删除成功",
            type: "success",
          });
          regainData();
        } else {
          ElMessage({
            message: res.msg,
            type: "error",
          });
        }
      });
    })
    .catch(() => {});
};
const clearData = () => {
  cleanLog().then((res) => {
    ElMessage.success("清空成功");
    regainData();
  });
};
// const unlock = () => {
//   unlockUser(curUser).then((res) => {
//     if (res.code == 200) {
//       ElMessage({
//         message: "解锁成功",
//         type: "success",
//       });
//       regainData();
//     } else {
//       ElMessage({
//         message: res.msg,
//         type: "error",
//       });
//     }
//   });
// };

// 导出
// const handleExport = () => {
//   console.log("导出");
//   exportLoginLog().then((res) => {
//     console.log(res);
//     downloadFile(
//       res,
//       "系统访问记录" + parseTime(new Date(), "{y}-{m}-{d} {h}:{i}") + ".xlsx"
//     );
//   });
// };

/** 排序触发事件 */
function handleSortChange(column, prop, order) {
  // filtrateData.value = {};
  filtrateData.value.orderByColumn = column.prop;
  filtrateData.value.isAsc = column.order;
  setCondition2();
}

// 操作分页器
const currentPage = ref(1);
const pageSize = ref(10);
const size = ref("default");
const total = ref(0);
const background = ref(false);
const disabled = ref(false);
const hide = ref(false);

const handleSizeChange = (val) => {
  console.log(`${val} items per page`);
  pageSize.value = val;
  getLoginLogList({ pageSize: val, pageNum: currentPage.value });
};
const handleCurrentChange = (val) => {
  console.log(`current page: ${val}`);
  currentPage.value = val;
  getLoginLogList({ pageSize: pageSize.value, pageNum: val });
};

const getLoginLogList = (data) => {
  return new Promise((resolve, reject) => {
    loading.value = true;
    getLogList(data)
      .then((res) => {
        if (res.code == 200) {
          console.log(res);
          tableData.value = res.rows;
          total.value = res.total;
          loading.value = false;
          resolve(res);
        }
      })
      .catch((err) => {
        loading.value = false;
        reject();
      });
  });
};
const regainData = () => {
  return getLoginLogList({
    pageSize: pageSize.value,
    pageNum: currentPage.value,
  });
};
const searchLog = (word, time) => {
  let params = {};
  if (word) {
    params.searchKey = word;
  }
  if (time) {
    params.startTime = time[0] ? time[0] + " 00:00:00" : null;
    params.endTime = time[1] ? time[1] + " 23:59:59" : null;
  }
  getLoginLogList({
    pageSize: pageSize.value,
    pageNum: 1,
    title:word,
    params,
  });
};
defineExpose({
  regainData,
  clearData,
  deleteSelectedLog,
  searchLog,
});
onMounted(() => {
  // 默认获取第一页的数据
  getLoginLogList({ pageSize: pageSize.value, pageNum: 1 });
});
</script>
<style lang="scss" scoped>
.icon {
  display: flex;

  > span {
    margin-right: 10px;
    display: flex;
    align-items: center;
    font-size: 18px;
  }

  .filtrateIcon,
  .reset {
    cursor: pointer;

    &:hover {
      color: #3973e5;
    }
  }
}

.manage_table {
  height: calc(100% - 60px);
  // padding: 20px 23px 0 26px;

  ._table {
    height: calc(100% - 100px);
  }

  .buttons {
    height: 40px;
    align-items: flex-start;

    .el-button {
      // width: 90px;
      // height: 30px;
      // background: url("@/assets/images/button.png") center/100% 100% no-repeat;
      border: none;
      // font-size: 18px;
      // color: #2c2c2c;
      // &:hover {
      //   color: #fff;
      // }
    }
  }

  :deep(.el-checkbox__inner) {
    width: 20px !important;
    height: 20px;

    &::after {
      width: 6px;
      height: 10px;
      top: 2px;
      left: 6px;
    }
  }

  // .page{
  .el-table__row {
    &:hover {
      background-color: aqua;
    }
  }

  // }
  .xh {
    width: 32px;
    height: 32px;
    border: 2px solid #767c80;
    border-radius: 50%;
    box-sizing: border-box;
    font-size: 16px;
  }

  // .handle_box{

  // }
  .el-pagination {
    margin-left: 20px;
  }
}

.el-button.is-link:hover {
  color: #3973e5;
}
</style>
